package com.lw.leetcode.arr.b;

/**
 * Created with IntelliJ IDEA.
 *
 * @author liw
 * @version 1.0
 * @date 2021/8/3 15:53
 */
public class FindUnsortedSubarray {




    public static void main(String[] args) {
        FindUnsortedSubarray test = new FindUnsortedSubarray();

        // 输入：nums = [2,6,4,8,10,9,15]   5
//        int[] arr = {2,6,4,8,10,9,15};

        //输入：nums = [1,2,3,4]  0
//        int[] arr = {1,2,3,4};

        //输入：nums = [1]  0
//        int[] arr = {1};

        // [-1,-1,-1,-1]  0
        int[] arr = {-1,-1,-1,-1};

        int unsortedSubarray = test.findUnsortedSubarray(arr);
        System.out.println(unsortedSubarray);
    }

    public int findUnsortedSubarray(int[] nums) {
        int st = 0;
        int end = -1;

        int endMax = Integer.MIN_VALUE;
        int stMin = Integer.MAX_VALUE;
        int length = nums.length;
        for (int i = 1; i < length; i++) {
            int val = nums[i];
            if (val < nums[i - 1]) {
                end = i;
                if (nums[i - 1] > endMax) {
                    endMax = nums[i - 1];
                }
            } else {
                if (val < endMax) {
                    end = i;
                }
            }
        }

        for (int i = length - 2; i >= 0; i--) {
            int val = nums[i];
            if (val > nums[i + 1]) {
                st = i;
                if (nums[i + 1] < stMin) {
                    stMin = nums[i + 1];
                }
            } else {
                if (val > stMin) {
                    st = i;
                }
            }
        }
        return end - st + 1;
    }


}
